package com.net.web.server.task;

import com.net.common.util.ThreadPoolFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.Set;

import static com.net.web.server.config.ServerMapContext.clientSocketMap;
import static com.net.web.server.config.ServerMapContext.proxyServerSocketMap;

@Component
@Slf4j
public class SocketTask {

    @Scheduled(cron = "0 0/3 * * * ?")
    private void execute() {
        Set<Long> clientSocketKey = clientSocketMap.keySet();
        if (CollectionUtils.isEmpty(clientSocketKey)) {
            proxyServerSocketMap.clear();
            return;
        }

        Set<Long> proxyServerRemoveSet = new HashSet<>();
        proxyServerSocketMap.forEach((key, value) -> {
            if (!clientSocketKey.contains(key)) {
                proxyServerRemoveSet.add(key);
            }
        });


        if (!CollectionUtils.isEmpty(proxyServerRemoveSet)) {
            for (Long key : proxyServerRemoveSet) {
                proxyServerSocketMap.remove(key);
            }
            log.info("删除无用代理数：{}", proxyServerRemoveSet.size());
        }

        log.info("当前在线客户端数量为：{},代理服务器数量为：{},最大线程数为:{},核心线程数为:{},活动线程数：{}", clientSocketKey.size(), proxyServerSocketMap.size(), ThreadPoolFactory.getMaximumPoolSize(), ThreadPoolFactory.getCorePoolSize(), ThreadPoolFactory.getActiveCount());

    }
}
